package com.hs.android.fortress.intro;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hs.android.fortress.model.RoomInformation;
import com.hs.android.fortress.net.AsyncNetworking;
import com.hs.android.fortress.net.FormPostCommand;
import com.hs.android.fortress.net.GetMethodCommand;
import com.hs.android.fortress.net.NetworkCommand;
import com.hs.android.fortress.net.ParamsMaker;
import com.hs.android.fortress.net.AsyncNetworking.onNetworkProcessListener;
import com.hs.android.fortress.GameApplication;
import com.hs.android.fortress.R;

public class PlayMenuFragment extends Fragment {
	private static final String TAG = "_PlayMenuFragment";

	private static final String DIALOG_ROOM = "room";
	public static final int REQUEST_ROOM = 0;

	private View fragmentUi;
	private Button btnCreateRoom, btnRefresh;
	private ListView listRoom;

	private GameApplication app;
	private String mUserId;
	private NetworkCommand mGetListCommand;

	private RoomAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (GameApplication) getActivity().getApplication();
		mUserId = app.getUserId();
		
		mGetListCommand = new GetMethodCommand("/room/list");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		fragmentUi = inflater.inflate(R.layout.fragment_menu_play, container,
				false);

		listRoom = (ListView) fragmentUi.findViewById(R.id.list_room);
		btnCreateRoom = (Button) fragmentUi.findViewById(R.id.btn_create_room);
		btnRefresh = (Button) fragmentUi.findViewById(R.id.btn_refresh);

		btnRefresh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				AsyncNetworking.newInstance(getActivity(), mGetListCommand, netListener).execute();

				Toast.makeText(getActivity(), "Refreshing the list",
						Toast.LENGTH_SHORT).show();
			}
		});

		btnCreateRoom.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				FragmentManager fm = getActivity().getFragmentManager();
				CreateRoomDialogFragment dialog = new CreateRoomDialogFragment();
				dialog.setTargetFragment(PlayMenuFragment.this, REQUEST_ROOM);
				dialog.show(fm, DIALOG_ROOM);
			}
		});

		return fragmentUi;
	}

	@Override
	public void onResume() {
		super.onResume();

		AsyncNetworking.newInstance(getActivity(), mGetListCommand, netListener).execute();
	}

	public void refreshListView(ArrayList<RoomInformation> roomList) {
		if(roomList != null){
			adapter = new RoomAdapter(roomList);
			listRoom.setAdapter(adapter);
	
			listRoom.setOnItemClickListener(new OnItemClickListener() {
	
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
										
					RoomInformation rInfo = (RoomInformation)parent.getAdapter().getItem(position);
					
					if(rInfo.getState() == RoomInformation.STATE_WAITING){
						Intent i = new Intent(getActivity(),WaitingRoomActivitiy.class);
						i.putExtra(WaitingRoomFragment.EXTRA_ROOM_NUMBER, rInfo.getRoomId());
						startActivity(i);
					}else{
						Toast.makeText(getActivity(), "This is playing state room....", Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
	}

	private class RoomAdapter extends ArrayAdapter<RoomInformation> {
		public RoomAdapter(ArrayList<RoomInformation> roomList) {
			super(getActivity(), R.layout.room_row, roomList);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			RoomHolder holder = null;

			if (row == null) {
				LayoutInflater inflater = getActivity().getLayoutInflater();

				row = inflater.inflate(R.layout.room_row, parent, false);
				holder = new RoomHolder(row);
				row.setTag(holder);
			} else {
				holder = (RoomHolder) row.getTag();
			}

			holder.populateFrom(getItem(position));

			return (row);
		}
	}

	private static class RoomHolder {
		private TextView txtStatus = null;
		private TextView txtId = null;
		private TextView txtRoom = null;
		private ImageView imgPlayers = null;

		public RoomHolder(View row) {
			txtStatus = (TextView) row.findViewById(R.id.txt_status);
			txtId = (TextView) row.findViewById(R.id.txt_id);
			imgPlayers = (ImageView) row.findViewById(R.id.img_players);
			txtRoom = (TextView) row.findViewById(R.id.txt_room);
		}

		void populateFrom(RoomInformation rInfo) {

			switch (rInfo.getState()) {
			case RoomInformation.STATE_PLAYING:
				txtStatus.setText("Playing...");
				break;
			case RoomInformation.STATE_WAITING:
				txtStatus.setText("Waiting...");
				break;
			}
			switch (rInfo.getPlayerNumber()) {
			case 1:
				imgPlayers.setBackgroundResource(R.drawable.player_1);
				break;
			case 2:
				imgPlayers.setBackgroundResource(R.drawable.player_2);
				break;
			case 3:
				imgPlayers.setBackgroundResource(R.drawable.player_3);
				break;
			}

			txtRoom.setText(rInfo.getRoomName());
			txtId.setText("Room Number : " + rInfo.getRoomId());
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK)
			return;
		if (requestCode == REQUEST_ROOM) {
			String roomName = data.getStringExtra(CreateRoomDialogFragment.EXTRA_ROOM_NAME);
			
			//create room
			AsyncNetworking.newInstance(getActivity(), new FormPostCommand("/room/create",ParamsMaker.makeCreateRoomParams(mUserId, roomName)), 
					new onNetworkProcessListener() {
						
						@Override
						public void onPostExecute(String result) {
							try{
								int roomNumber = Integer.parseInt(result);
								Intent i = new Intent(getActivity(),WaitingRoomActivitiy.class);
								i.putExtra(WaitingRoomFragment.EXTRA_ROOM_NUMBER, roomNumber);
								startActivity(i);
							}catch(NumberFormatException e){
								AsyncNetworking.makeNetworkProblemDialog(getActivity()).
									setTitle("Problem").
									setMessage("Network Proble or Your position doesn't set Yet..").
									setPositiveButton("OK", null).
									create().show();
							}
						}
					}).execute();
			
			
		}
	}

	onNetworkProcessListener netListener = new onNetworkProcessListener() {

		@Override
		public void onPostExecute(String result) {
			if(result != null){
				ArrayList<RoomInformation> roomList = null;
				
				try {
					JSONArray jarr = (JSONArray)new JSONTokener(result).nextValue();
					
					roomList = new ArrayList<RoomInformation>();
					
					for(int i = 0 ; i < jarr.length() ; i++){
						RoomInformation room = JSONToRoomInfomation(jarr.getJSONObject(i).toString());
						roomList.add(room);
					}
					
					refreshListView(roomList);
				} catch (JSONException e) {
					Log.e(TAG,"Json exception : ",e);
				}
			}else{
				AsyncNetworking.makeNetworkProblemDialog(getActivity()).
				setPositiveButton("OK", null).
				create().show();
			}
		}
	};
	
	private RoomInformation JSONToRoomInfomation(String json) {
		Gson gson = new Gson();		 
		RoomInformation rInfo = gson.fromJson(json, RoomInformation.class);		
		return rInfo; 
	}

}